import re
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from pymysql import DatabaseError

from apps.users.models import User
from utils.response_code import RETCODE


class index(View):
    def get(self,request):
        return render(request,'register.html')
    # 接收注册后传过来的数据
    def post(self,request):
        # 接收参数
        username=request.POST.get('username')
        password=request.POST.get('password')
        password2=request.POST.get('password2')
        mobile=request.POST.get('mobile')
        allow=request.POST.get('allow')
        # 判断是否补全
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseForbidden('参数不全')
        # 判断姓名是否符合格式
        if not re.match(r'^\w{5,20}',username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')
        # 保持状态
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})
        # 保持状态
        login(request,user)
        # 响应注册结果
        return redirect(reverse('contents:index'))


class UsernameCountView(View):
    '''用户名重复注册'''
    def get(self,request,username):
        '''判断用户名是否存在'''
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

class MobileCountView(View):
    '''验证手机号是否存在'''
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

